<template>
  <div id="app2">
         <img src="" alt="falseimg" style="position:absolute;left:-100000px;" id="falseImg">
         <el-form  enctype="multipart/form-data" class="demo-ruleForm" status-icon :show-message="false" :rules="rules" ref="ruleForm" :model="this.formdata" label-width="95px">
          <div class="formlist" style="margin-top:10px;" id='face-responsice-height'>
                <el-form-item label="身份证正面照" prop="carDrivingNum" style="width:120px;">
                        <div style="height:120px;">
                            <div  class="paizhao" id='face-paizhao'> 
                                <div id="upimgdefault" style="display:none;">
                                  <img id="img1-tupian" src="" alt="1" width="150" height="100px">
                               </div> 
                                <i id="paizhaodefault" class="el-icon-picture-outline"></i>
                                <div class="upfile">
                                    <input type="file" value="path" id="input1-tupian" @change="upimg('#img1-tupian','#input1-tupian','face')" accept="image/*">
                                </div>  
                            </div>
                        </div>
                 </el-form-item> 
            </div>
            <div class="formlist" style="margin-top:10px;" id='back-responsice-height'>
                <el-form-item label="身份证背面照" prop="carDrivingNum">
                        <div style="height:120px;">
                            <div  class="paizhao" id='back-paizhao'> 
                                <div id="upimgdefault" style="display:none;">
                                  <img id="img2-tupian" src="" alt="2" width="150" height="100">
                                </div> 
                                <i id="paizhaodefault"   class="el-icon-picture-outline"></i>
                                <div class="upfile">
                                    <input type="file" id="input2-tupian" @change="upimg('#img2-tupian','#input2-tupian','back')" accept="image/*">
                                </div>  
                            </div>
                        </div>
                 </el-form-item> 
            </div>
            <div class="formlist">
                <el-form-item label="姓名" prop="name">
                        <input v-model="formdata.name" ref="name" readonly style='font-size:18px;'></input>
                 </el-form-item>
            </div> 
            <div class="formlist">
                    <el-form-item label="身份证号" prop="idNum">
                            <input v-model="formdata.idNum" ref="idNum" readonly style='font-size:18px;'></input>
                        </el-form-item>
                        <span v-if='formdata.idNum' style="color:red;font-size:11px">请认真核对姓名和身份证号码,不一致请重新上传图片</span>
            </div> 
            <div class="formlist">
                    <el-form-item label="手机号"  prop="mobile">
                            <input type="mobile" placeholder="请填写手机号" v-model="formdata.mobile" style='font-size:18px;'></input>
                        </el-form-item>
            </div> 
            <div class="formlist">
                 <el-form-item label="验证码" prop="code">
                     <el-col :span="12">
                         <el-form-item id="change-margin-left1" prop="code">
                                <input placeholder="输入验证码" v-model="formdata.code" style='font-size:18px;'></input>
                         </el-form-item>
                     </el-col>
                     <el-col :span="12" style="text-align: right;">
                            <el-form-item >
                                  <el-button id="change-margin-left2"  @click="sendmsg($event)" :disabled="this.showcodebtn"  round size="mini">获取验证码</el-button>
                            </el-form-item>
                     </el-col> 
                </el-form-item>
            </div> 
             <div class="formlist">
                    <el-form-item label="邀请码"  prop="code">
                            <input type='text' placeholder="请输入邀请码" v-model="invatationCode" style='font-size:18px;'></input>
                    </el-form-item>
            </div> 
            <div class="formlist">
                    <el-form-item label="商户名"  prop="code">
                            <input type='text' v-model="fullName" readonly style='font-size:18px;'></input>
                    </el-form-item>
            </div> 
             <div style="text-align: center; width:100%;margin-top:15px;">
                <el-button @click="submitForm()" :loading="this.formbtnLoding" type="primary"  style="width:92%;">立即申请</el-button>
             </div>
        </el-form>
        <br> 
  </div>
</template>
<script>
import { comm_default } from "../comm/comm.js";
export default {
  beforeCreate: function() {
    $("title").text("填写资料");
  },
  data: function() {
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(""));
      } else if (value !== this.formdata.cardNum) {
        callback(new Error(""));
      } else {
        callback();
      }
    };
    return {
      off:false,
      invatationCode:'',
      fullName:'',
      yanzheng:false,
      merchantCode:'',
      files:[
        {
          zhenfan:'face',
          value:''
        },
        {
          zhenfan:'back',
          value:''
        }
      ],
      showcodebtn: false,
      formbtnLoding: false,
      formdata: {
        carDrivingImg: "",
        name: "",
        idNum: "",
        mobile: "",
        code: "",
        querenyouka: "",
        carDrivingNum: "",
        cardNum: "",
        userId: $.cookie("userid")
      },
      rules: {
        name: [
          { required: true, message: "", trigger: "blur" },
          { min: 2, max: 6, message: "", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "", trigger: "blur" },
          { min: 11, max: 11, message: "", trigger: "blur" }
        ],
        idNum: [{ required: true, message: "", trigger: "blur" }],
        code: [{ required: true, message: "", trigger: "blur" }],
        carDrivingNum: [{ required: true, message: "", trigger: "blur" }],
        cardNum: [{ required: true, message: "", trigger: "blur" }],
        querenyouka: [
          { required: true, message: "", trigger: "blur" },
          { validator: validatePass2, trigger: "blur" }
        ]
      }
    };
  },
  watch:{
    'invatationCode'(val){
      let This=this;
      if(val.length===6){
        $.get(`${comm_default.requestSH}/merchants/getMerchants?inviteCode=${val}`,function(data){
          if(data.executed){
            This.merchantCode=data.merchantCode
            This.fullName=data.fullName;
          }else{
            This.merchantCode=' ';
            This.fullName=' ';
            layer.open({
                content: '邀请码无效',
                skin: "msg",
                time: 3 //2秒后自动关闭
            });
          }
        })
      }
    }
  },
  mounted: function() {
    setTimeout(function() { 
      var h = $(window).height();
      $("#app2").css("min-height",h+"px");
      $('.el-form-item__label').css('width','120px');
      $('.el-form-item__content').css('margin-left','120px');
      $('#change-margin-left1 .el-form-item__content:first').css('margin-left','0');
      $('#change-margin-left2').css('padding','7px 7px');
      $('#change-margin-left2').parent().css('margin-left','0');
    }, 300);
  },
  methods: {
    submitForm: function() {
      var th = this;
      let send={
        userName:this.formdata.name,
        userCard:this.formdata.idNum,
        faceFiles:JSON.stringify(this.files[0].value.fileResInfo),
        backFiles:JSON.stringify(this.files[1].value.fileResInfo),
        openId:$.cookie("user_openid"),  
        // openId:'oAxlv0mgaH1Al_2kNioQw4bVSSMY',
        userPhone:this.formdata.mobile,
        merchantCode:this.merchantCode
      };
      if(this.off){
        this.openBindingFail("执行失败");
        return ;
      }
      for(let i in send){
        let valOff=String(send[i]).trim();
        if(!valOff||valOff=='null'||valOff=='undefined'){
          this.openBindingFail("执行失败");
          return ;
        }
      }
      let faceFiles=[{
           fileName:this.files[0].value.fileResInfo.oldName,
           path:this.files[0].value.fileResInfo.path,
           fileSize:this.files[0].value.fileResInfo.size,
           fileSufix:this.files[0].value.fileResInfo.newName.split('.')[1]
      }];
      let backFiles=[{
           fileName:this.files[1].value.fileResInfo.oldName,
           path:this.files[1].value.fileResInfo.path,
           fileSize:this.files[1].value.fileResInfo.size,
           fileSufix:this.files[1].value.fileResInfo.newName.split('.')[1]
      }];
      send.faceFiles=JSON.stringify(faceFiles);
      send.backFiles=JSON.stringify(backFiles);
      //调用短信验证接口 
      $.post(`${comm_default.requestComm}/sms/checkSMSCode?type=REGISTER`,{
        mobile:this.formdata.mobile,
        code:this.formdata.code
      },function(data){
        if(data.executed){
            //调用增值接口来存信息       http://192.168.0.105:8032 ${comm_default.requestSH}
            $.post(`${comm_default.requestSH}/userOilCardInfo/save`,send,function(data1){ 
              if(data1.executed){
                th.$router.push({path:'/index3'});
              }else{
                th.openBindingFail('服务器错误');
              }
            });
        }else{
          th.openBindingFail('验证码错误');
        }
      })
    },
    upimg: function(imgel,inputel,zhenfan) {
        let This=this;
        if(zhenfan=='face'){
          This.formdata.name='';
          This.formdata.idNum='';
        }
        
        //scale 原图的宽高度比例 width/height
        var file = $(inputel).get(0).files[0];
        function getBase64Image(img) {  
             //原生的图片节点  注意：是<img>标签
             var width = img.width,height = img.height;
             var scale = width / height;
             var chAfHei=$(imgel).width()/scale;
             let startHei=$.cookie('elStartHei');
             let elPi=$('#'+zhenfan+'-responsice-height');
             //这个是超出了改变最外层父级高
             if(chAfHei-100>0){ 
               if(startHei){
                  elPi.height(parseFloat(startHei)+chAfHei-100);
               }else{
                 let elHei=elPi.height();
                 $.cookie('elStartHei',elHei);
                 elPi.height(elHei+chAfHei-100);
               }
             }else if(startHei){
                 elPi.height(parseFloat(startHei));
             }
             //下面这三句是不管超出与否，虚线始终和图片一样宽高
             $('#'+zhenfan+'-paizhao').height(chAfHei);
             $(imgel).attr('height',chAfHei);
             $(imgel).parent().show();
             $(imgel).parent().next().hide();
             //压缩出来的宽度是400  高度是按照比例来自适应的
             var width1 = 400;
             var height1 = parseInt(width1 / scale);
             var canvas = document.createElement("canvas");   
             canvas.width = width1; /*设置新的图片的宽度*/  
             canvas.height = height1; /*设置新的图片的长度*/  
             var ctx = canvas.getContext("2d");  
             ctx.drawImage(img, 0, 0, width1, height1); /*绘图*/  
             //压缩质量是0.5
             var dataURL = canvas.toDataURL("image/png", 0.8);  
             //返回的是一个base64的字符串串
             return dataURL; 
         }
         var reader = new FileReader();
         reader.onloadend = function () {
            $(imgel).attr('src',reader.result);
            $('#falseImg').attr('src',reader.result);
         }
         if (file) {
           reader.readAsDataURL(file);
         } else {
           $(imgel).attr('src','');
         }
         setTimeout(function(){
          let shengfengcanshu={
              sIamgeData:getBase64Image($('#falseImg').get(0)),
              sFaceRect:zhenfan
          };
          $.post(`${comm_default.requestSH}/checkIdCard`,shengfengcanshu,function(data){
                if(!data.success||data.faceRect!=zhenfan){
                   This.openBindingFail("请传正确的身份证");
                   This.off=true;
                   return;
                }else{
                  This.off=false;
                  if(data.faceRect=='face'){
                    This.formdata.name=data.perSoname;
                    This.formdata.idNum=data.idNum;
                  }
                  let formData = new FormData();
                   formData.append('info',file);
                   //再调用远程图片得到结果
                   $.ajax({
                      url: `${comm_default.requestComm}/file/upload`,
                      type: 'POST',
                      cache: false,
                      data: formData,
                      processData: false,
                      contentType: false,
                      success: function(data1){
                        console.log('tuoan');
                        console.log(data1);
                        if(data1.success){
                          This.off=false;
                          This.files[0].zhenfan==zhenfan?(This.files[0].value=data1):(This.files[1].value=data1);
                        }else{
                          This.openBindingFail("请传正确的身份证");
                          This.off=true;
                          return ;
                        }
                      }
                    });
                }
            });
        },800)
    },
    openBindingFail(info){
      layer.open({
          content: info,
          skin: "msg",
          time: 3 //2秒后自动关闭
       });
    },
    //发送验证码
    sendmsg: function(ev) {
      if(this.yanzheng){
        return ;
      }
      var th = this;

       var tel = th.formdata.mobile;
        if (tel == "") {
          layer.open({
            content: "请先输入手机号码",
            skin: "msg",
            time: 3 //2秒后自动关闭
          });
          return;
        }
        if(!th.formdata.idNum){
          layer.open({
            content: "请重新上传身份证照",
            skin: "msg",
            time: 3 //2秒后自动关闭
          });
          return;
        }
        th.yanzheng=true;
        //检测手机号是否注册过    ${comm_default.requestSH}   http://192.168.0.105:8032
      $.post(`${comm_default.requestSH}/userOilCardInfo//checkPhoneIdCard`,{
        code:'12',
        userPhone:tel,
        userCard:th.formdata.idNum
      },function(data){

          if(!data.executed){
              th.yanzheng=false;
              th.off=true;
              th.openBindingFail(data.message);
              return ;
          }else{

              th.off=false;
              //发送短信
              $.post(`${comm_default.requestComm}/sms/getSMSCode?type=REGISTER`,{
                mobile:tel
              },function(data1){
                 if (data1.executed) {
                    th.off=false;
                    var s = 70;
                    var t = setInterval(() => {
                      $(ev.target).text(`【${s}】秒`);
                      if (s == 0) {
                        th.showcodebtn = false;
                        th.yanzheng=false;
                        $(ev.target).text("获取验证码");
                        clearInterval(t);
                      }
                      s--;
                    }, 1000);
                  } else {
                    th.yanzheng=false;
                    th.showcodebtn = false;
                    th.off=true;
                    layer.open({
                      content: data1.message,
                      skin: "msg",
                      time: 3 //2秒后自动关闭
                    });
                  }
              });
          }
      }); 
    },
  }
};
function xhrup(file) {
  this.xhr = new XMLHttpRequest();
  this.init = function() {
    var th = this;
    var fileObj = file; // js 获取文件对象
    var form = new FormData(); // FormData 对象
    form.append("file1", fileObj); // 文件对象
    th.xhr.open("post", "http://192.168.0.19:8031/file/upload", true); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
    th.xhr.onload = th.uploadComplete; //请求完成
    th.xhr.onerror = th.uploadFailed; //请求失败
    th.xhr.send(form); //开始上传，发送form数据
  };
  this.uploadComplete = function(evt) {
  };
  this.uploadFailed = function(evt) {
    alert("上传失败");
  };
}
</script>
<style>
input:focus{
  outline: none;
}
#app2 .formlist {
  padding: 10px 15px 10px 15px;
  background-color: white;
  border-bottom: 1px solid #f1f0f0;
  height: auto;
}
#app2 .formlist input {
  border: 0px;
}
#app2 .formlist .el-form-item {
  margin-bottom: 0px;
}
#app2 .formlist .paizhao {
  position: relative;
  width: 150px;
  height: 100px;
  border: 1px dashed #ccc;
  margin-top: 15px;
  margin-left: 15px;
  text-align: center;
  line-height: 100px;
  color: #ccc;
  font-size: 40px;
}
#app2 .formlist .paizhao .upfile {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100px;
  line-height: 0px;
  opacity: 0;
}
#app2 .formlist .paizhao .upfile input {
  width: 100%;
  height: 100px;
}
#app2 .formlist .el-form-item__label {
  text-align: left;
}
</style>


